#coding=utf-8
from django.contrib import messages, auth
from django.contrib.auth import authenticate
from django.contrib.auth.models import User, Group
from django.core.urlresolvers import reverse

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from DjangoBbs.Common.Permission import isSiteManager
from DjangoBbs.SiteSetting.models import SiteExtcredit
from PublicTool import HttpWrite
from PublicTool.ViewHelper import ViewHelper
import models
import forms
__author__ = 'czq'

def _login(request,username,password):
    '''登陆核心方法'''
    ret=False
    user=authenticate(username=username,password=password)
    if user:
        if user.is_active:
            auth.login(request,user)
            ret=True
        else:
            messages.add_message(request, messages.INFO, u'用户没有激活')
            return u'用户没有激活'
    else:
        messages.add_message(request, messages.INFO, u'用户不存在')
        return u'用户名或密码错误'
    return ret


class UsersView(ViewHelper):
    def __init__(self):
        self.moduleName='Users'
        self.typeName='users'
    def get_model(self):
        return User
    def checkUser(self,form):
        nameUser=User.objects.filter(username__iexact=form.cleaned_data["username"])
        if nameUser:
            return u'用户名已经被占用'
        emailUser=User.objects.filter(email__iexact=form.cleaned_data["email"])
        if emailUser:
            return u"邮箱已经注册"
        if form.cleaned_data["password1"]!=form.cleaned_data["password1"]:
            return u"两次输入密码不一致"
        return
    #注册
    def register(self,request):
        dict={}
        import forms
        if (request.method=="POST"):
            form=forms.UserRegisterForm(request.POST)
            if form.is_valid():
                check = self.checkUser(form)
                #raise Exception,check
                if check:
                    dict["info"] = check
                else:
                    username=form.cleaned_data["username"]
                    password=form.cleaned_data["password1"]
                    user=User.objects.create_user(username,form.cleaned_data["email"],password)
                    user.save()
                    #
                    user=User.objects.get(username=username)
                    #raise Exception,user.id
                    group=Group.objects.all()[0]
                    profile=models.UserProfile(user=user,nickName=u'新用户'+username[:2],group=group)
                    profile.save()
                    #userinfo
                    userInfo=models.UserInfo(user=user)
                    userInfo.save()
                    #setting
                    userSetting=models.UserSetting(user=user)
                    userSetting.save()
                    _login(request,username,password)
                    return HttpResponseRedirect(reverse("bbsClass_list"))
                #form.save()
        else:
            form=forms.UserRegisterForm
            #dict["info"] = u"注册用户！"
        dict["form"]=form
        return render_to_response("Users/users_register.html",dict,context_instance=RequestContext(request))
    #登陆
    def login(self,request):
        dict={}
        import forms
        if request.method=="POST":
            form=forms.UserLoginForm(request.POST)
            if form.is_valid():
                username=form.cleaned_data["username"]
                password=form.cleaned_data["password1"]
                l= _login(request,username,password)
                if l==True:
                    url=request.GET.get('url','')
                    if url!='':
                        return super(UsersView,self).showUrl(url)
                    return HttpResponseRedirect(reverse("bbsClass_list"))
                else:
                    dict["info"]=l
        else:
            form=forms.UserLoginForm
        dict["form"]=form
        return render_to_response("Users/users_login.html",dict,context_instance=RequestContext(request))
    #注销
    def logout(self,request):
        auth.logout(request)
        return HttpResponseRedirect(reverse("bbsClass_list"))
    #设置
    def setting(self,request,id=''):
        if id=='':
            id=request.user.id
        else:
            if id==request.user.id:
                pass
            else:
                if not isSiteManager(request):
                    return HttpWrite.infoSuccess(request,u"不存在的页面")
                #return HttpWrite.infoSuccess(request,"没有此用户！")
        user=get_object_or_404(self.get_model(),pk=int(id))
        if request.method=="POST":
            userProfileForm=forms.UserProfileForm(request.POST,instance=models.UserProfile.objects.get(user=user))
            userInfoForm=forms.UserInfoForm(request.POST,instance=models.UserInfo.objects.get(user=user))
            userSettingForm=forms.UserSettingForm(request.POST,instance=models.UserSetting.objects.get(user=user))
            if userProfileForm.is_valid():
                userProfileForm.save()
            if userInfoForm.is_valid():
                userInfoForm.save()
            if userSettingForm.is_valid():
                userSettingForm.save()
        else:

            userProfileForm=forms.UserProfileForm(instance=models.UserProfile.objects.get(user=user))
            userInfoForm=forms.UserInfoForm(instance=models.UserInfo.objects.get(user=user))
            userSettingForm=forms.UserSettingForm(instance=models.UserSetting.objects.get(user=user))
        dict={'userProfileForm':userProfileForm,'userInfoForm':userInfoForm,'userSettingForm':userSettingForm}
        return render_to_response("Users/users_setting.html",dict,context_instance=RequestContext(request))
    def users_manage(self,request,id=''):
        user=User.objects.get(id=id)
        #raise Exception,
        instance=models.UserProfile.objects.get(user=user)
        dict={}
        if request.method=="POST":
            oldGroup = instance.group
            form=forms.UserManageForm(request.POST,instance=instance)
            if form.is_valid():
                profile=form.save()
                #raise Exception,oldGroupName+profile.group.name
                if oldGroup.name!=profile.group.name:
                    user.groups.remove(oldGroup)
                    user.groups.add(profile.group)
                    dict['info']=u'权限保存成功！'
                else:
                    dict['info']=u'保存成功！'
        else:
            form=forms.UserManageForm(instance=instance)
            #dict['info']=user.has_perm('BbsTheme.add_bbsclass')#user.has_perm('foo.add_bar')  #user.groups.all()[0].permissions.all()  #user.has_perm('BbsTheme.add_bbsclasstype')
        dict['instance']=instance
        dict['form']=form
        #raise Exception,instance.id
        return render_to_response("Users/users_manage.html",dict,context_instance=RequestContext(request))

    #主题
    def users_theme(self,request):
        dict={}
        return render_to_response("Users/users_theme_list.html",dict,context_instance=RequestContext(request))
    #回复
    def users_theme_reply(self,request):
        dict={}
        return render_to_response("Users/users_theme_reply_list.html",dict,context_instance=RequestContext(request))

    def list(self,request):
        return super(UsersView,self).list(request)
    def show_get_dict(self,request,instance):
        dict={}
        extcreditList = SiteExtcredit.objects.all()[:2]

        if extcreditList:
            for item in extcreditList:

                dict["extcredit%d_name"%item.number]=item.name
                dict["extcredit%d_unit"%item.number]=item.unit
        #dict["extcreditList"]=extcreditList
        return dict
    #def show_submit(self,request,instance):
    #    try:
    #        instance.get_profile()
    #    except:
    #        profile=models.UserProfile(user=instance)
    #        profile.save()
    def show(self,request,id):
        return super(UsersView,self).show(request,id)


class GroupsView(ViewHelper):
    def __init__(self):
        self.moduleName='Users'
        self.typeName='groups'
    def get_model(self):
        return models.GroupProfile

    def add_get_form(self,request):
        return forms.GroupForm

    def show_get_dict(self,request,instance):
        form=forms.GroupForm(readonly_fields=['themeBusinessExtcreditMax','fileSingleMaxSize','perm',],instance=instance)
        dict={'form':form}
        return dict
    #def show_submit(self,request,instance):
    #    raise Exception,instance
    def list(self,request):
        return super(GroupsView,self).list(request)